package com.sphd.emanu.fragment.mine;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sphd.emanu.R;
import com.sphd.emanu.activity.AboutActivity;
import com.sphd.emanu.activity.changepwd.ChangePwdActivity;

import com.sphd.emanu.activity.login.LoginActivity;
import com.sphd.emanu.activity.orgsetting.OrgSettingActivity;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.interfaces.LetterAtoF;
import com.sphd.emanu.mvp.MVPBaseFragment;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.imageselect.PicassoImageLoader;
import com.sphd.emanu.view.RoundImageView;
import com.sphd.emanu.view.siderbar.SortModel;
import com.wzutils.SPUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class MineFragment extends MVPBaseFragment<MineContract.View, MinePresenter> implements MineContract.View {

    private static final String TAG = "MineFragment";
    @BindView(R.id.mine_edit_pwd)
    TextView mineEditPwd;
    @BindView(R.id.mine_about)
    TextView mineAbout;
    @BindView(R.id.mine_cancel)
    TextView mineCancel;
    @BindView(R.id.mine_quite_out)
    TextView mineQuiteOut;
    Unbinder unbinder;
    Intent intent;
    @BindView(R.id.shop_setting)
    TextView shopSetting;
    @BindView(R.id.layout_heard)
    LinearLayout layoutHeard;
    @BindView(R.id.user_img)
    RoundImageView userImg;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_roliename)
    TextView userRoliename;

    private GalleryConfig galleryConfig;
    private IHandlerCallBack iHandlerCallBack;
    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;
    private List<String> path = new ArrayList<>();
    User user;
    Bundle bundle;
    LetterAtoF letterAtoF;

    public void setLetterAtoF(LetterAtoF letterAtoF) {
        this.letterAtoF = letterAtoF;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this, rootView);
        intent = new Intent();
        bundle = getArguments();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        if (user.getRoleid().equals("1") || user.getRoleid().equals("2")) {
            shopSetting.setVisibility(View.VISIBLE);
        }
        userName.setText(user.getUsername());
        userRoliename.setText(user.getRolename());
        setImage(userImg, Constant.HTTPTITLE_Base + user.getImgpath(),R.mipmap.moren_head);
        initGallery();
        init();
    }

    private void init() {
        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.sphd.emanu.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(true)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(true, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();
    }

    @Override
    protected void initData() {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.layout_heard, R.id.shop_setting, R.id.mine_edit_pwd, R.id.mine_about, R.id.mine_cancel, R.id.mine_quite_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_heard:
                initPermissions();
                break;
            case R.id.shop_setting:
                intent.putExtras(bundle);
                intent.setClass(context, OrgSettingActivity.class);
                startActivity(intent);
                break;

            case R.id.mine_edit_pwd:
                bundle.putBoolean(Constant.CHANGE_PWD, true);
                intent.setClass(context, ChangePwdActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.mine_about:
                intent.putExtras(bundle);
                intent.setClass(context, AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.mine_cancel:

                new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("确定要注销登录吗？")
                        .setConfirmText("确定").setConfirmClickListener(sweetAlertDialog1 -> {

                    if (SPUtils.contains(context, Constant.LOGIN_PWD)) {
                        SPUtils.remove(context, Constant.LOGIN_PWD);
                    }
                    intent.setClass(context, LoginActivity.class);
                    startActivity(intent);
                    sweetAlertDialog1.dismiss();
                    letterAtoF.finishActivity();
                }).setCancelText("算了").show();


                break;
            case R.id.mine_quite_out:
                System.exit(0);
                break;
        }

    }

    /**
     * 跳转返回的数据
     */
    private void initGallery() {
        iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                Log.i(TAG, "onStart: 开启");
            }

            @Override
            public void onSuccess(List<String> photoList) {
                Log.e(TAG, "onSuccess: 返回数据");
                path.clear();
                for (String s : photoList) {
                    Log.e(TAG + "->>>", s);
                    path.add(s);
                }
                if (path.size() != 0) {
                    showProgressDialog();
                    mPresenter.updateUserImage(user.getUserid(), prepareFilePart("image", path.get(0)));
                }
            }

            @Override
            public void onCancel() {
                toast("取消");
                Log.e(TAG, "onCancel: 取消");
            }

            @Override
            public void onFinish() {
                Log.e(TAG, "onFinish: 结束");
            }

            @Override
            public void onError() {
                toast("出错了，请重试！");
                Log.e(TAG, "onError: 出错");
            }
        };

    }

    // 授权管理
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "需要授权 ");
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Log.e(TAG, "拒绝过了");
                toast("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                Log.e(TAG, "进行授权");
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            Log.e(TAG, "不需要授权 ");
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).open((Activity) context);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "同意授权");
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open((Activity) context);
            } else {
                Log.e(TAG, "拒绝授权");
            }
        }
    }

    @Override
    public void setRes(int res) {
        dissProgressDialog();
        if (res == 1) {
            toast("上传成功");
            setImage(userImg, "file://" + path.get(0));
        } else {
            toast("上传失败，请重试！");
            setImage(userImg, Constant.HTTPTITLE_Base + user.getImgpath());
        }
    }
}
